import { fileURLToPath } from 'node:url'
import { writeFile, readdir } from 'node:fs/promises'

import tsconfig from '../tsconfig.json'

const Path = {
  packagesPath: fileURLToPath(new URL('../packages', import.meta.url)),
  tsAppConfigPath: fileURLToPath(new URL('../tsconfig.json', import.meta.url))
}

updateTsconfigPaths('ginkgo')

async function updateTsconfigPaths(scoped: string) {
  console.log('🧭 Updating tsconfig paths...')

  const packages = await readdir(Path.packagesPath)

  const paths = packages.reduce<Record<string, [string]>>((acc, name) => {
    const packageName = `@${scoped}/${name}`
    return {
      ...acc,
      [packageName]: [`./packages/${name}/src/index.ts`],
      [`${packageName}/*`]: [`./packages/${name}/src/*`]
    }
  }, {})

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  tsconfig.compilerOptions.paths = paths
  await writeFile(Path.tsAppConfigPath, JSON.stringify(tsconfig, null, 2))

  console.table(paths)
  console.log('✅ Paths update success!')
}
